<template>
  <!-- 加载状态 -->
  <motion-div
    v-if="isPolling && !data"
    :initial="{ opacity: 0, y: 20 }"
    :animate="{ opacity: 1, y: 0 }"
    :exit="{ opacity: 0, y: -20 }"
    class="flex items-center justify-center p-4 bg-blue-50 rounded-lg"
  >
    <div class="animate-spin rounded-full h-5 w-5 border-2 border-blue-500 border-t-transparent mr-3" />
    <span class="text-blue-700">正在分析解题步骤...</span>
  </motion-div>

  <!-- 错误状态 -->
  <motion-div
    v-else-if="error"
    :initial="{ opacity: 0, y: 20 }"
    :animate="{ opacity: 1, y: 0 }"
    class="p-4 bg-red-50 rounded-lg border border-red-100"
  >
    <div class="flex items-start">
      <AlertCircle class="h-5 w-5 text-red-500 mt-0.5 mr-3" />
      <p class="text-red-700">{{ error.message }}</p>
    </div>
  </motion-div>

  <!-- 正常状态 -->
  <div v-else-if="data" class="space-y-4">
    <div :class="`p-4 rounded-lg ${
      data.isCorrect 
        ? 'bg-green-50 border border-green-100' 
        : 'bg-yellow-50 border border-yellow-100'
    }`">
      <div class="flex items-start">
        <component 
          :is="data.isCorrect ? CheckCircle : AlertCircle"
          class="h-5 w-5 mt-0.5 mr-3"
          :class="data.isCorrect ? 'text-green-500' : 'text-yellow-500'"
        />
        
        <div class="flex-1">
          <h3 :class="`font-medium ${
            data.isCorrect ? 'text-green-800' : 'text-yellow-800'
          }`">
            {{ data.isCorrect ? '解题思路正确' : '需要改进' }}
          </h3>
          <p :class="`text-sm mt-1 ${
            data.isCorrect ? 'text-green-700' : 'text-yellow-700'
          }`">
            {{ data.feedback }}
          </p>

          <!-- 建议步骤 -->
          <div v-if="data.suggestedSteps" class="mt-3">
            <h4 class="text-sm font-medium text-gray-700 mb-2">
              建议步骤：
            </h4>
            <ul class="space-y-1">
              <li 
                v-for="(step, index) in data.suggestedSteps"
                :key="index"
                class="text-sm text-gray-600 flex items-center"
              >
                <span class="w-5 h-5 rounded-full bg-gray-200 flex items-center justify-center text-xs mr-2">
                  {{ index + 1 }}
                </span>
                {{ step }}
              </li>
            </ul>
          </div>

          <!-- 演示功能 -->
          <div v-if="data.demonstration" class="mt-4">
            <button
              @click="toggleDemonstration"
              class="flex items-center px-3 py-1.5 text-sm font-medium rounded-md bg-white shadow-sm border border-gray-200 hover:bg-gray-50"
            >
              <component 
                :is="isDemonstrating ? Pause : Play"
                class="w-3.5 h-3.5 mr-1.5"
              />
              {{ isDemonstrating ? '暂停演示' : '查看正确解法' }}
            </button>

            <div v-if="isDemonstrating" class="mt-3 p-3 bg-white rounded-md shadow-sm">
              <div class="flex items-center justify-between text-sm text-gray-500 mb-2">
                <span>步骤 {{ currentDemoStep + 1 }}/{{ data.demonstration.steps.length }}</span>
                <span>{{ Math.round((currentDemoStep + 1) / data.demonstration.steps.length * 100) }}%</span>
              </div>
              <div class="w-full h-1 bg-gray-200 rounded-full">
                <div
                  class="h-full bg-blue-500 rounded-full transition-all duration-300"
                  :style="{
                    width: `${((currentDemoStep + 1) / data.demonstration.steps.length) * 100}%`
                  }"
                />
              </div>
              <p class="mt-2 text-sm text-gray-700">
                {{ data.demonstration.steps[currentDemoStep].description }}
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount } from 'vue';
// import { motion } from 'framer-motion';
import { 
  AlertCircle, 
  CheckCircle, 
  Play, 
  Pause 
} from 'lucide-vue-next';

const motionDiv = motion('div');

const props = defineProps({
  operations: {
    type: Array,
    required: true,
    default: () => []
  },
  problemType: {
    type: String,
    required: true
  }
});

const emit = defineEmits(['feedback', 'verificationResult']);

const data = ref(null);
const error = ref(null);
const isPolling = ref(false);
const isDemonstrating = ref(false);
const currentDemoStep = ref(0);
let pollingInterval = null;
let demoInterval = null;

// 开始轮询验证
const startPolling = async () => {
  isPolling.value = true;
  error.value = null;
  
  try {
    const result = await aiService.verifySolution(props.operations, props.problemType);
    data.value = result;
    emit('feedback', result.feedback);
    emit('verificationResult', result);
  } catch (err) {
    error.value = err;
  } finally {
    isPolling.value = false;
  }
};

// 停止轮询
const stopPolling = () => {
  if (pollingInterval) {
    clearInterval(pollingInterval);
    pollingInterval = null;
  }
};

// 切换演示状态
const toggleDemonstration = () => {
  isDemonstrating.value = !isDemonstrating.value;
  currentDemoStep.value = 0;
};

// 设置演示定时器
const setupDemoInterval = () => {
  if (demoInterval) clearInterval(demoInterval);
  
  if (isDemonstrating.value && data.value?.demonstration) {
    demoInterval = setInterval(() => {
      currentDemoStep.value = prev => {
        const next = prev + 1;
        if (next >= data.value.demonstration.steps.length) {
          isDemonstrating.value = false;
          return 0;
        }
        return next;
      };
    }, 2000);
  }
};

// 监听操作变化
watch(() => props.operations, (newVal) => {
  if (newVal.length > 0) {
    startPolling();
  }
}, { immediate: true });

// 监听演示状态变化
watch(isDemonstrating, (newVal) => {
  setupDemoInterval();
});

onBeforeUnmount(() => {
  stopPolling();
  if (demoInterval) clearInterval(demoInterval);
});
</script>

<style scoped>
/* 自定义动画 */
.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
